#include"shm.h"


int shm_init(char**addr)
{
    // 创建key值
    key_t key = ftok("/lib", 'a');
    if (key < 0)
    {
        perror("ftok error");
        return -1;
    }
   // printf("key=%#x\n", key);
    // 创建共享内存
    int shmid = shmget(key, 128, IPC_CREAT | IPC_EXCL | 0666);
    if (shmid <= 0)
    {
        if (errno == EEXIST)
            shmid = shmget(key, 128, 0666); // 打开
        else
        {
            perror("shmget failed");
            return -1;
        }
    }
    if (shmid < 0)
    {
        perror("shmget error");
        return -1;
    }
    //printf("shmid=%d\n", shmid);
    // 将共享内存映
    *addr = (char*)shmat(shmid, NULL, 0);
    if (NULL ==*addr)
    {
        perror("shmat error");
        return -1;
    }
    return shmid;  
}
